﻿using Application.Adapter;
using Application.Plugins;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace DeviceService
{

    /// <summary>
    /// 做成服务端单独项目，和api分离
    /// </summary>
    public class DeviceService : IHostedService
    {
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var service = CreateService();
            while (true)
            {
                Console.WriteLine("service running");
                await Task.Delay(3000);
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }
        private static TcpService CreateService()
        {
            var service = new TcpService();
            service.Connecting = (client, e) => { };//有客户端正在连接
            service.Connected = (client, e) => { };//有客户端成功连接
            service.Disconnected = (client, e) => { };//有客户端断开连接

            service.Setup(new TouchSocketConfig()//载入配置
                .SetListenIPHosts("tcp://192.168.0.38:6638")//同时监听两个地址
                .SetTcpDataHandlingAdapter(() => new CustomBetweenAndDataHandlingAdapter())
                .ConfigureContainer(a =>//容器的配置顺序应该在最前面
                {
                    a.AddConsoleLogger();//添加一个控制台日志注入（注意：在maui中控制台日志不可用）
                    a.RegisterSingleton(service);//将服务器以单例注入。便于插件或其他地方获取。
                })
                .ConfigurePlugins(a =>
                {
                    a.Add<ReceivePlugin>();
                }))
                .Start();//启动
            return service;
        }
    }
}
